/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package session;

import entity.Customer;
import entity.CustomerOrder;
import entity.OrderItem;
import java.util.Collection;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Declan
 */
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class OrderManager {
    
    @PersistenceContext(unitName = "PhoneShopPU")
    private EntityManager em;

    @Resource
    private SessionContext sessionContext;

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public Long placeOrder(String firstName,
            String lastName, String address,
            int phoneNumber, Collection<OrderItem> orderItems)
    {
        try {
            Customer customer = addCustomer(firstName, lastName,
                    address, phoneNumber);
            CustomerOrder order = addOrder(customer, orderItems);
            return order.getId();
        } catch(Exception ex) {
            sessionContext.getRollbackOnly();
            return -1L;
        }
        
    }

    private Customer addCustomer(String firstName,
            String lastName, String address,
            int phoneNumber)
    {
        Customer customer = new Customer(firstName, lastName, address, phoneNumber);
        em.persist(customer);
        return customer;
    }

    private CustomerOrder addOrder(Customer customer, Collection<OrderItem> orderItems)
    {
        for(OrderItem item : orderItems) {
            em.persist(item);
        }
        CustomerOrder order = new CustomerOrder(customer, orderItems);
        em.persist(order);
        return order;
    }



 
}
